<?php

namespace App\Http\Controllers\API;

use App\Models\FamousTeacher;
use App\Models\FamousTeacherHasFile;
use App\Models\File;
use App\Models\Teacher;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class FamousTeacherController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function index(Request $request)
    {
        $keyword = $request->get('keyword', '');
        $query = FamousTeacher::query()->when($keyword , function ($queryString) use ($keyword) {
            return $queryString->join('xyj_teachers' , 'teacher_user_id' , '=' , 'xyj_teachers.user_id')->select('xyj_famous_teachers.*')
                ->where('xyj_teachers.name' , 'like' , '%'.$keyword.'%')->orWhere('xyj_teachers.mobile' , 'like' , '%' . $keyword . '%')
                ->orWhere('xyj_teachers.school_cn' , 'like' , '%'.$keyword.'%');
        })->with('teacher')->orderBy('sort');

        $models = $query->paginate();
        return $models;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * @param Request $request
     * @return FamousTeacher|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function store(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data,
            [
                'teacher_user_id' => 'required',
                'sort' => 'required'
            ],
            [
                'teacher_user_id.required' => '老师必填',
                'sort.required' => '排序必填'
            ]
        );

        if ($validator->fails()) {
            $errors = $validator->errors();
            return response($errors, 422);
        }

        $model = new FamousTeacher();
        $model->fill($data);
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $model = $this->findModel($id);
        $model->teacher;
        $model->file;
        return $model;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->all();
        $validator = Validator::make($data,
            [
                'teacher_user_id' => 'required',
                'sort' => 'required'
            ],
            [
                'teacher_user_id.required' => '老师必填',
                'sort.required' => '排序必填'
            ]
        );

        if ($validator->fails()) {
            $errors = $validator->errors();
            return response($errors, 422);
        }

        $model = $this->findModel($id);
        $model->fill($data);
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }

    /**
     * @param $id
     * @return array
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            if ($model->delete()) {
                return ['state' => 'success'];
            }
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }

    /**
     * @param $id
     * @return mixed
     */
    protected function findModel($id)
    {
        $model = FamousTeacher::find($id);
        return $model;
    }

    /**
     * @param Request $request
     * @param $famousTeacherId
     * @return FamousTeacherHasFile|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function fileUpload(Request $request, $famousTeacherId)
    {
        $data = $request->all();
        $validator = Validator::make($data,
            [
                'file' => 'required',
                'point_url' => 'required',
                'title' => 'required'
            ],
            [
                'file.required' => '图片未上传',
                'point_url.required' => '指向url必填',
                'title.required' => '标题必填'
            ]
        );

        if ($validator->fails()) {
            $errors = $validator->errors();
            return response($errors, 422);
        }
        $file = $request->file('file');
        if ($file) {
            $img = new File();
            $img->type = '名师图片';
            $img->size = $file->getSize();
            $path = Storage::put('famous-teachers', $file);
            if ($path) {
                $img->path = $img->key = $path;
                $img->filename = pathinfo($path, PATHINFO_BASENAME);
                $img->extension = pathinfo($path, PATHINFO_EXTENSION);
            } else {
                return response(['upload_failed' => '上传失败'], 422);
            }
            if ($img->save()) {
                $model = new FamousTeacherHasFile();
                $model->famous_teacher_id = $famousTeacherId;
                $model->fill($data);
                $model->files_id = $img->id;
                if ($model->save()) {
                    return ['status' => 'success'];
                } else {
                    return response($model->getErrors()->toArray(), 406);
                }
            } else {
                return response($img->getErrors()->toArray(), 406);
            }
        }
    }

    /**
     * @param $famousTeacherId
     * @param $fileId
     * @return array
     */
    public function deleteTeacherFile($famousTeacherId, $fileId)
    {
        $file = File::find($fileId);
        $model = FamousTeacherHasFile::where('famous_teacher_id', $famousTeacherId)->where('files_id', $fileId)->first();
        if ($model) {
            try {
                $model->delete();
                $file->delete();
                Storage::delete($file->path);
                return ['state' => 'success'];
            } catch (\Exception $e) {
                return ['state' => 'failed', 'message' => $e->getMessage()];
            }
        }
    }



    public function getTeacherInfo($teacherMobile)
    {
        $teacher  = Teacher::where('mobile' , $teacherMobile)->first();
        if ($teacher){
            return $teacher;
        }else{
            return response(['search_failed' => '查无此人！'], 422);
        }
    }


    public function getImgList($famousTeacherId)
    {
        $model = $this->findModel($famousTeacherId);
        return $model->file;
    }
}
